//这是一个单色材质，存在一个颜色动态参数

#version 460
#extension GL_ARB_separate_shader_objects : enable
#extension GL_ARB_shading_language_420pack : enable

//layout (set=0 ,binding = 0) uniform sampler2D Texture2Ds[]; //texture2D 参数
layout (set=0 ,binding = 0) uniform SFloatParameters  ////float 参数, 图片数量不为0，binding=0, 否则binding=1
{
    vec4 Floats[];
} FloatParameters;


layout (location = 0) in vec3 inNormal;
layout (location = 1) in vec2 inUV;
layout (location = 2) in vec3 inWorldPos;
layout (location = 3) in float inCameraNearPlane;
layout (location = 4) in float inCameraFarPlane;

layout (location = 0) out vec4 outAlbedo;
layout (location = 1) out vec4 outPosition;
layout (location = 2) out vec4 outNormal;
layout (location = 3) out vec4 outMisc;

float linearDepth(float depth)
{
	float z = depth * 2.0f - 1.0f; 
	return (2.0f * inCameraNearPlane * inCameraFarPlane) / (inCameraFarPlane + inCameraNearPlane - z * (inCameraFarPlane - inCameraNearPlane));	
}

//ref：https://learnopengl.com/PBR/Theory
vec3 GetNormalFromMap(vec3 InNormalTextureValue)
{
    vec3 tangentNormal=InNormalTextureValue*2.0-1.0; // convert from range(0,1) to range(-1,1)
    
    vec3 Q1  = dFdx(inWorldPos);
    vec3 Q2  = dFdy(inWorldPos);
    vec2 st1 = dFdx(inUV);
    vec2 st2 = dFdy(inUV);

    vec3 N   = normalize(inNormal);
    vec3 T  = normalize(Q1*st2.t - Q2*st1.t);
    vec3 B  = -normalize(cross(N, T));
    mat3 TBN = mat3(T, B, N);

    return normalize(TBN * InNormalTextureValue);
}

void main() 
{ 
    vec3 Albedo;
    float Metallic=.5f;
    float Roughness=.5f;
    float Ao=1.f;
    vec3 NormalTextureValue=vec3(0,0,1);

    Albedo=FloatParameters.Floats[0].xyz;

	vec3 Normal=GetNormalFromMap(NormalTextureValue);
	
    outMisc.r = linearDepth(gl_FragCoord.z);
	outNormal = vec4(Normal, Roughness);
	outPosition = vec4(inWorldPos, Metallic);
	outAlbedo=vec4(Albedo,Ao);
    // Write color attachments to avoid undefined behaviour (validation error)
    //outColor = vec4(0.0);
}